/**
 *
 */
package com.pocketsweet.ui;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.LogInCallback;
import com.avos.avoscloud.PushService;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.util.HanziToPinyin;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.chatui.MLHXSDKHelper;
import com.pocketsweet.chatui.domain.User;
import com.pocketsweet.chatui.utils.CommonUtils;
import com.pocketsweet.dao.SystemConfigManager;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.utils.MD5;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * @author hantian 闪屏界面
 */
public class Splash extends Activity {
    private static final int sleepTime = 2000;
    private RelativeLayout rootLayout;
    private ImageView imgFlash;
    private ImageView imgSplash;
    private ImageView imgAppName;
    private boolean isLogin = false;
    // Frame动画
    private AnimationDrawable animDance;
    public MLApplication mlApplication;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
            finish();
            return;
        }
        mlApplication = MLApplication.getInstance();
        if (mlApplication.isHasActivity() == true) {
            Splash.this.finish();
            return;
        }
        setContentView(R.layout.activity_flash);
        rootLayout = (RelativeLayout) findViewById(R.id.splash_root);
        imgFlash = (ImageView) findViewById(R.id.imgFlash);
        imgAppName = (ImageView) findViewById(R.id.imgAppName);
        imgSplash = (ImageView) findViewById(R.id.imgSplash);
        animDance = (AnimationDrawable) imgFlash.getBackground();
        animDance.start();
        imgAppName.setImageDrawable(getResources().getDrawable(
                R.drawable.img_app_name));
        AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
        animation.setDuration(200);
        // imgSplash.setAnimation(animation);
        // animation.setAnimationListener(new AnimationImpl());

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        // ToolKits.toast(Splash.this, "屏幕分辨率为:" + dm.widthPixels + " * "
        // + dm.heightPixels);// 查看手机分辨率
    }

    // private class AnimationImpl implements AnimationListener {
    //
    // @Override
    // public void onAnimationStart(Animation animation) {
    // }
    //
    // @Override
    // public void onAnimationEnd(Animation animation) {
    // skip(); // 动画结束后跳转到别的页面
    // }
    //
    // @Override
    // public void onAnimationRepeat(Animation animation) {
    //
    // }
    //
    // }
    //
    // private void skip() {
    // startActivity(new Intent(this, OtherActivity.class));
    // finish();
    // }

    @Override
    protected void onStart() {
        super.onStart();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (SystemConfigManager.getInstance(Splash.this).isFirstRun()) {
                    // 直接跳到主界
                    Intent intent = new Intent(Splash.this, Welcome.class);
                    // // 从启动动画ui跳转到主ui
                    startActivity(intent);
                    // 结束启动动画界面
                    Splash.this.finish();
                } else {
                    if (!CommonUtils.isNetWorkConnected(Splash.this)) {
                        ToolKits.toast(Splash.this, "世界上最遥远的距离就是断网");
                    } else {
                        final MLUser currentUser = UserService.getCurrentUser();
                            String user = MLContext.getUserLogin("user");
                            String pwd = MLContext.getUserLogin("pass");
                            String uid = MLContext.getUserLogin("uid");
                            String type = MLContext.getUserLogin("type");
                            String access_token = MLContext
                                    .getUserLogin("access_token");
                            // Log.e("==login","==login==user:"+user);
                            // Log.e("==login","==login==pwd:"+pwd);
                            // Log.e("==login","==login==uid:"+uid);
                            // Log.e("==login","==login==type:"+type);
                            // Log.e("==login","==login==access_token:"+access_token);
                            if (!user.equals("") && !pwd.equals("")) { // 若user和密码不为空，直接登陆
                                // Log.e("==login", "==login==can save normal");
                                MLUser.logInInBackground(user, pwd,
                                        new LogInCallback<AVUser>() {

                                            @Override
                                            public void done(AVUser user,
                                                             AVException e) {
                                                if (e == null) {
                                                    if (MLCache
                                                            .getCache()
                                                            .getAsJSONObject(
                                                                    UserService
                                                                            .getCurrentUserId()) == null) {
                                                        MLHXSDKHelper.getInstance()
                                                                .logout(null);
                                                        Intent intent = new Intent(
                                                                Splash.this,
                                                                TempMain.class); // 从启动动画ui跳转到主ui
                                                        startActivity(intent);
                                                        Splash.this.finish();
                                                        return;
                                                    }
                                                    if (UserService
                                                            .getCurrentUser()
                                                            .getStatus() == C.USER_STATUS_DISABLE) {
                                                        ToolKits.toast(Splash.this,
                                                                "对不起该账号已被查封");
                                                        Intent intent = new Intent(
                                                                Splash.this,
                                                                TempMain.class); // 从启动动画ui跳转到主ui
                                                        startActivity(intent);
                                                        Splash.this.finish();
                                                        return;
                                                    }
                                                    if (UserService
                                                            .getCurrentUser()
                                                            .getIsInited() != 1) {
                                                        ToolKits.toast(Splash.this,
                                                                "您的账号信息不全，请先完善信息");
                                                        Intent r = new Intent(
                                                                Splash.this,
                                                                CreateUserInfo.class);
                                                        startActivity(r);
                                                        finish();
                                                        return;
                                                    }
                                                    if (MLHXSDKHelper.getInstance()
                                                            .isLogined()) {
                                                        // ** 免登陆情况 加载所有本地群和会话
                                                        // 不是必须的，不加sdk也会自动异步去加载(不会重复加载)；
                                                        EMChatManager
                                                                .getInstance()
                                                                .deleteConversation(
                                                                        Constant.NEW_CHAT_APPLY);// 删掉通话申请
                                                        if (UserService
                                                                .getCurrentUser()
                                                                .getType() != C.USER_TYPE_NORMAL) {
                                                            EMChatManager
                                                                    .getInstance()
                                                                    .deleteConversation(
                                                                            Constant.NEW_FRIENDS_USERNAME);// 删掉好友申请
                                                        }
                                                        initChannel();
                                                        AVCloud.callFunctionInBackground("getNetTime", null,
                                                                new FunctionCallback<Long>() {

                                                                    @Override
                                                                    public void done(Long time, AVException e) {
                                                                        if (e == null) {
                                                                            Date currentDate = new Date(time);
                                                                            MLUser currentUser = new MLUser();
                                                                            currentUser.setObjectId(UserService.getCurrentUserId());
                                                                            currentUser.setLastLoginTime(currentDate); // 设置最后登陆时间
                                                                            currentUser.saveInBackground();
                                                                        }
                                                                    }

                                                                });
                                                        EMChatManager
                                                                .getInstance()
                                                                .loadAllConversations();
                                                        MLApplication.getInstance()
                                                                .setIsLogin(true);
                                                        Intent intent = new Intent(
                                                                Splash.this,
                                                                Main.class); // 从启动动画ui跳转到主ui
                                                        startActivity(intent);
                                                        // 结束启动动画界面
                                                        Splash.this.finish();
                                                    } else {
                                                        loginHuanxin();
                                                    }

                                                } else {
                                                    if (e.getCode() == 215) {// 未验证手机号
                                                        ToolKits.toast(Splash.this,
                                                                "未验证手机号");
                                                        Intent r = new Intent(
                                                                Splash.this,
                                                                VerifySmsCode.class);
                                                        Splash.this
                                                                .startActivity(r);
                                                    } else if (e.getCode() == 210) {
                                                        ToolKits.toast(Splash.this,
                                                                "密码错误，请重新填写");
                                                        Intent intent = new Intent(
                                                                Splash.this,
                                                                TempMain.class); // 从启动动画ui跳转到主ui
                                                        startActivity(intent);
                                                        Splash.this.finish();
                                                    } else if (e.getCode() == 211
                                                            || e.getCode() == 213) {
                                                        ToolKits.toast(Splash.this,
                                                                "用户不存在，请重新登陆");
                                                        Intent intent = new Intent(
                                                                Splash.this,
                                                                TempMain.class); // 从启动动画ui跳转到主ui
                                                        startActivity(intent);
                                                        Splash.this.finish();
                                                    } else if (e.getCode() == 1) {
                                                        ToolKits.toast(Splash.this,
                                                                "请输入你的密码");
                                                        Intent intent = new Intent(
                                                                Splash.this,
                                                                TempMain.class); // 从启动动画ui跳转到主ui
                                                        startActivity(intent);
                                                        Splash.this.finish();
                                                    } else {
                                                        ToolKits.toast(Splash.this,
                                                                "亲爱的，您的网络似乎断开了");
                                                    }
                                                    // Intent intent = new Intent(
                                                    // Splash.this, Main.class);
                                                    // // 从启动动画ui跳转到主ui
                                                    // startActivity(intent);
                                                    // // 结束启动动画界面
                                                    // Splash.this.finish();
                                                }
                                            }
                                        });
                            } else if (!uid.equals("") && !access_token.equals("")
                                    && !type.equals("")) { // 若uid,type,access_token不为空,第三方登陆
                                // Log.e("==login", "==login==can save 3");
                                if (MLCache.getCache().getAsJSONObject(
                                        UserService.getCurrentUserId()) == null) {
                                    MLHXSDKHelper.getInstance().logout(null);
                                    Intent intent = new Intent(Splash.this,
                                            TempMain.class); // 从启动动画ui跳转到主ui
                                    startActivity(intent);
                                    Splash.this.finish();
                                    return;
                                }// 更新完需要重新登陆
                                thirdLogin(); // 第三方登陆
                            } else {
                                // Log.e("==login", "==login==can not save");
                                Intent intent = new Intent(Splash.this,
                                        TempMain.class); // 从启动动画ui跳转到主ui
                                startActivity(intent);
                                // 结束启动动画界面
                                Splash.this.finish();
                            }
                        }
                    }
                }
            // 结束启动动画界面
        }, 200); // 启动动画持续2秒钟
    }

    String uid;
    String type;
    String access_token;

    protected void thirdLogin() {
        uid = MLContext.getUserLogin("uid");
        type = MLContext.getUserLogin("type");
        access_token = MLContext.getUserLogin("access_token");
        AVUser.AVThirdPartyUserAuth auth = new AVUser.AVThirdPartyUserAuth(
                access_token, "", type, uid);
        AVUser.loginWithAuthData(auth, new LogInCallback<AVUser>() {

            @Override
            public void done(AVUser arg0, AVException e) {
                // TODO Auto-generated method stub
                if (e == null) {
                    if (MLCache.getCache().getAsJSONObject(
                            UserService.getCurrentUserId()) == null) {
                        MLHXSDKHelper.getInstance().logout(null);
                        Intent intent = new Intent(Splash.this, TempMain.class); // 从启动动画ui跳转到主ui
                        startActivity(intent);
                        Splash.this.finish();
                        return;
                    }
                    // 恭喜你，已经和我们的AVUser绑定成功
                    if (UserService.getCurrentUser().getStatus() == C.USER_STATUS_DISABLE) {
                        ToolKits.toast(Splash.this, "对不起该账号已被查封");
                        Intent intent = new Intent(Splash.this, TempMain.class); // 从启动动画ui跳转到主ui
                        startActivity(intent);
                        Splash.this.finish();
                        return;

                    } else {
                        // Log.e("=succeed=",
                        // "duang!!!!!!!!!");
                        // 登录成功，保存账号和密码

                        if (UserService.getCurrentUser().getIsInited() != 1) {
                            ToolKits.toast(Splash.this, "您的账号信息不全，请先完善信息");
                            Intent r = new Intent(Splash.this,
                                    CreateUserInfo.class);
                            // r.putExtra("nickname",
                            // info.get("screen_name").toString());
                            // //
                            // r.putExtra("gender",
                            // //
                            // info.get("gender").toString());
                            // r.putExtra("location",
                            // info.get("location")
                            // .toString());
                            // r.putExtra("profile_image_url",
                            // info.get("profile_image_url").toString());
                            startActivity(r);
                            finish();
                            return;
                        } else {
                            MLApplication.getInstance().setIsLogin(true);
                            ShareReferanceUtils share = new ShareReferanceUtils(
                                    MLApplication.getContext(), "USER");
                            share.setStringValue("access_token", access_token);
                            share.setStringValue("uid", uid);
                            share.setStringValue("type", type);
                            loginHuanxin();// 登陆环信
                        }
                        // Intent infoInent = new
                        // Intent(
                        // VerifySmsCode.this,
                        // CreateUserInfo.class);
                        // VerifySmsCode.this.startActivity(infoInent);
                    }
                } else {// 登录失败
                    if (e.getCode() == 251) {// 授权access token过期
                        ToolKits.toast(Splash.this, "授权过期，请重新授权登录");
                        Intent intent2 = new Intent(Splash.this, TempMain.class);
                        startActivity(intent2);
                        Splash.this.finish();
                    }
                    // 退订之后需要重新保存 Installation
                    // MLApplication.getInstance().logout(new EMCallBack() {
                    //
                    // @Override
                    // public void onSuccess() {
                    // runOnUiThread(new Runnable() {
                    // public void run() {
                    // // 重新显示登陆页面
                    // MLUser.logOut();
                    // MLContext.deleteAll(); // 删除所有sharepreference
                    // Intent intent2 = new Intent(Splash.this,
                    // Login.class);
                    // startActivity(intent2);
                    // Splash.this.finish();
                    // Main.getInstance().finish();
                    // }
                    // });
                    // }
                    //
                    // @Override
                    // public void onProgress(int progress, String status) {
                    //
                    // }
                    //
                    // @Override
                    // public void onError(int code, String message) {
                    //
                    // }
                    // });
                    e.printStackTrace();
                }

            }
        });
    }

    private void loginHuanxin() {
        // 登陆环信聊天
        EMChatManager.getInstance().login(UserService.getCurrentUserId(),
                MD5.md5(UserService.getCurrentUser().getObjectId()),
                new EMCallBack() {

                    @Override
                    public void onSuccess() {
                        MLUser currentUser = UserService.getCurrentUser();
                        AVCloud.callFunctionInBackground("getNetTime", null,
                                new FunctionCallback<Long>() {

                                    @Override
                                    public void done(Long time, AVException e) {
                                        if (e == null) {
                                            Date currentDate = new Date(time);
                                            MLUser currentUser = new MLUser();
                                            currentUser.setObjectId(UserService.getCurrentUserId());
                                            currentUser.setLastLoginTime(currentDate); // 设置最后登陆时间
                                            currentUser.saveInBackground();
                                        }
                                    }

                                });
                        MLApplication.getInstance().setIsLogin(true);
                        // 用户关注channel
                        initChannel();
                        EMChatManager.getInstance().deleteConversation(
                                Constant.NEW_CHAT_APPLY);// 删掉通话申请
                        if (currentUser.getType() != C.USER_TYPE_NORMAL) {
                            EMChatManager.getInstance().deleteConversation(
                                    Constant.NEW_FRIENDS_USERNAME);// 删掉好友申请
                        }
                        try {
                            // **
                            // 第一次登录或者之前logout后再登录，加载所有本地群和回话
                            // ** manually load all
                            // local groups
                            // and
                            // conversations in case we
                            // are auto
                            // login
                            EMChatManager.getInstance().loadAllConversations();
                            // 处理好友和群组
                            // processContacts();
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 取好友或者群聊失败，不让进入主页面
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    MLApplication.getInstance().logout(null);
                                    ToolKits.toast(getApplicationContext(),
                                            R.string.login_failure_failed);
                                    Intent infoInent = new Intent(Splash.this,
                                            TempMain.class);
                                    startActivity(infoInent);
                                    ((Activity) Splash.this).finish();
                                }
                            });
                            return;
                        }
                        // 更新当前用户的nickname
                        // 此方法的作用是在ios离线推送时能够显示用户nick
                        boolean updatenick = EMChatManager.getInstance()
                                .updateCurrentUserNick(
                                        MLApplication.currentUserNick.trim());
                        if (!updatenick) {
                            // Log.e("LoginActivity",
                            // "update current user nick fail");
                        }
                        if (!Splash.this.isFinishing())
                            // 进入主页面
                            isLogin = true;
                        Intent intent = new Intent(Splash.this, Main.class);
                        Splash.this.startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onProgress(int progress, String status) {
                    }

                    @Override
                    public void onError(final int code, final String message) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                isLogin = false;
                                logOut();
                                ToolKits.toast(getApplicationContext(),
                                        R.string.login_failure_failed);
                                Intent infoInent = new Intent(Splash.this,
                                        TempMain.class);
                                startActivity(infoInent);
                                ((Activity) Splash.this).finish();
                            }
                        });
                    }
                });
    }

    private void initChannel() {
        PushService.subscribe(Splash.this, UserService.getCurrentUserId(), Splash.class);
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.subscribe(Splash.this, "SweetMale", Main.class);
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.subscribe(Splash.this, "SweetFemale", Main.class);
            }
        }

    }

    private void setUserHearder(String username, User user) {
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance()
                    .get(headerName.substring(0, 1)).get(0).target.substring(0,
                            1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }

    }

    protected void logOut() {
        MLUser.logOut();
        MLApplication.getInstance().logout(null);
        cancleChannel(); // 退订之后需要重新保存 Installation
        AVInstallation.getCurrentInstallation().saveInBackground();
        MLApplication.getInstance().logout(new EMCallBack() {

            @Override
            public void onSuccess() {
                Splash.this.runOnUiThread(new Runnable() {
                    public void run() {
                        // 重新显示登陆页面
                        MLContext.deleteAll(); // 删除所有sharepreference
                    }
                });
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {

            }
        });
    }

    private void cancleChannel() {
        PushService.unsubscribe(Splash.this, UserService.getCurrentUserId());
        if (UserService.getCurrentUser() == null) {
            return;
        }
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.unsubscribe(Splash.this, "SweetMale");
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.unsubscribe(Splash.this, "SweetFemale");
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStop() {
        super.onStop();
        releaseImageViews();

    }

    private void releaseImageViews() {
        releaseImageView(imgAppName);
    }

    private void releaseImageView(ImageView imageView) {
        Drawable d = imageView.getDrawable();
        if (d != null)
            d.setCallback(null);
        imgAppName.setImageDrawable(null);
        imgAppName.setBackgroundDrawable(null);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}
